//
//  WBHomePictureView.swift
//  WB123
//
//  Created by xuyunde mac pro on 2017/7/4.
//  Copyright © 2017年 NSObjiect. All rights reserved.
//

import UIKit
import SDWebImage

// cell间距
private let cellMarin: CGFloat = 5
// 计算cell的宽高
private let cellWH = (SCREENW - 20 - 2 * cellMarin)/3
// cell可重用标识符
private let cellId = "cellId"
class WBHomePictureView: UICollectionView {

    // 提供一个模型数据 供外界赋值
    var picUrlsList: [WBPicurlModel]?{
        didSet{
//            print("图片个数--",picUrlsList?.count)
            // 计算size
            let size = dealPictureViewSizeWith(count: picUrlsList!.count)
            
            //通过图片个数更新配图的大小的约束
            snp.updateConstraints { (make) in
                make.size.equalTo(size)
            }
            reloadData()
        }
    }
    
    //MARK: - 通过配图数组的count 来计算配图的size
    private func dealPictureViewSizeWith(count: Int) -> CGSize{
       
        //拿到flowLayout
        // 拿到flowLayout
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        //是否一张图
        if count == 1 {
            // 从本地磁盘中获取本地图片
            if let urlString = picUrlsList?.first?.thumbnail_pic {
                
                if let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: urlString){
                    
                    //获取图片的宽和高
                    var imageW = image.size.width
                    var imageH = image.size.height
                    //过窄
                    if imageW < 80 {
                        imageW = 80
                    }
                    //过长
                    if imageH > 150 {
                        imageH = 150
                    }
                    // 重新设置
                    flowLayout.itemSize = CGSize(width: imageW, height: imageH)
                    //返回
                    return CGSize(width: imageW, height: imageH)
                }
            }
            
        }
        
        //通过count计算其他行列
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        
        //计算宽高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1)*cellMarin
        let h = CGFloat(row) * cellWH + CGFloat(row - 1)*cellMarin
        
        // 重新设置
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        return CGSize(width: w, height: h)
    }
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        // 计算itemSize
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        // 设置垂直水平i间距
        flowLayout.minimumLineSpacing = cellMarin
        flowLayout.minimumInteritemSpacing = cellMarin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 设置视图
    private func setupUI(){
        
        dataSource = self
        register(WBHomePictureViewCell.self, forCellWithReuseIdentifier: cellId)
        // 为了防止崩溃 可以设置一个默认约束
        snp.makeConstraints { (make) in
            make.size.equalTo(CGSize(width: cellWH, height: cellWH))
        }

    }
   
}

//MARK: - 自定义cell
extension WBHomePictureView: UICollectionViewDataSource{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrlsList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! WBHomePictureViewCell
        cell.picurlModel = picUrlsList![indexPath.item]
        return cell
    }
}

class WBHomePictureViewCell: UICollectionViewCell {
    
    // 提供属性 供外界赋值
    var picurlModel: WBPicurlModel?{
        didSet{
            // 赋值
            bgImageView.wb_setImage(withUrlString: picurlModel?.thumbnail_pic, placeholderImgName: nil)
            guard let thumbnail_pic = picurlModel?.thumbnail_pic else {
                return
            }
            // 是否显示git图片标志
            gifImageView.isHidden = !thumbnail_pic.hasSuffix("gif")
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        backgroundColor = UIColor.white
        // 添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        // 添加约束
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp.makeConstraints { (make) in
            make.right.bottom.equalTo(contentView)
        }
    }
    
    // 懒加载
    private lazy var bgImageView: UIImageView = {
        let img = UIImageView(named: "timeline_image_placeholder")
        // 图片填充方式
         img.contentMode = .scaleAspectFill
        img.clipsToBounds = true
        return img
    }()
    // gif图片
    private lazy var gifImageView: UIImageView = UIImageView(named: "timeline_image_gif")
}
